<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-1/4 xl:w-1/5 m-4 mr-0 overflow-hidden bg-white pr-2">
      <BasicTree
        title="模块"
        :treeData="treeDataList"
        defaultExpandLevel="1"
        treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
        @select="treeHandleSelect"
        :selected-keys="selectedKeys"
        ref="treeRef"
      />
    </div>
    <BasicTable
      @register="registerTable"
      @fetch-success="onFetchSuccess"
      class="w-3/4 xl:w-4/5 m-4"
      :search-info="searchInfo"
    >
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增菜单 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'material-symbols:add-box-outline',
                tooltip: '增加子菜单',
                onClick: handleAdd.bind(null, record),
              },
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑菜单',
                onClick: handleEdit.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <MenuDrawer @register="registerDrawer" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { nextTick, h, onMounted, ref, reactive, unref } from 'vue';

  import { PageWrapper } from '@/components/Page';
  import { BasicTree, TreeActionType, TreeItem, TreeActionItem } from '@/components/Tree';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useDrawer } from '@/components/Drawer';
  import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

  import MenuDrawer from './MenuDrawer.vue';
  import { treeData } from './data';
  import { columns } from './menu.data';
  import { getMenuList, deleteMenuByIds } from '@/api/system/menu';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { ModuleTreeItem } from './tree_module';
  import { getDictionaryList } from '@/api/system/dictionary';

  defineOptions({ name: 'MenuManagement' });
  const { createMessage } = useMessage();
  const [registerDrawer, { openDrawer }] = useDrawer();

  const searchInfo = reactive<Recordable>({});
  const [registerTable, { reload, expandAll }] = useTable({
    title: '菜单列表',
    api: getMenuList,
    columns,
    isTreeTable: true,
    pagination: false,
    striped: false,
    bordered: true,
    size: 'small',
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: 'right',
    },
    handleSearchInfoFn(info) {
      searchInfo.module_id = 0;
      return info;
    },
  });

  const treeRef = ref<Nullable<TreeActionType>>(null);
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  function handleCreate() {
    openDrawer(true, {
      isUpdate: false,
    });
  }

  function handleAdd(record: Recordable) {
    console.log(record);
    openDrawer(true, {
      id: record?.id,
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  /**
   * 删除菜单
   * @param record
   */
  async function handleDelete(record: Recordable) {
    const { t } = useI18n();
    const id: any = record?.id;
    const { code, message } = await deleteMenuByIds(id);
    if (code == 0) {
      createMessage.success(t('sys.api.deleteSuccess'));
      reload();
    } else {
      createMessage.error(message);
    }
  }

  function handleSuccess() {
    reload();
  }

  function onFetchSuccess() {
    // 演示默认展开所有表项 expandAll
    nextTick(expandAll);
  }

  const actionList: TreeActionItem[] = [
    {
      // show:() => boolean;
      render: (node) => {
        return h(PlusOutlined, {
          class: 'ml-2',
          onClick: () => {
            console.log('onlick add', node.key);
          },
        });
      },
    },
    {
      render: () => {
        return h(DeleteOutlined);
      },
    },
  ];

  function treeHandleSelect(selectedKeys, e) {
    console.log(selectedKeys[0], e);
    searchInfo.module_id = selectedKeys[0];
    reload();
  }

  const selectedKeys = ref<number[]>([]);
  const treeDataList = ref<TreeItem[]>([]);
  onMounted(async () => {
    selectedKeys.value = [];
    const { items } = await getDictionaryList({ parent_id: 33, order_by: 'order_no:asc' });
    items.forEach((item) => {
      if (selectedKeys.value.length == 0) {
        selectedKeys.value.push(Number(item.id));
      }
      treeDataList.value.push({
        title: item.name,
        key: item.id,
        icon: item.remark,
        children: [],
      });
    });

    // getTree().setSelectedKeys([38]);
    // const keys = getTree().getSelectedKeys();
    // console.log(keys);
    // if (keys.length && keys[0]) {
    //   searchInfo.module_id = keys[0];
    // }
  });
</script>
